﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace SoftSource.Common
{
    public static class GenericExtensions
    {
        public static bool TryDeepCopy<T>(this T source, out T copy)
        {
            return source.TryDeepCopy(out copy, ex => { });
        }

        /// <summary>
        /// Atttempt to copy a full object graph.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="copy"></param>
        /// <param name="onFailure"></param>
        /// <returns></returns>
        public static bool TryDeepCopy<T>(this T source, out T copy, Action<Exception> onFailure)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(ms, source);

                    ms.Seek(0, SeekOrigin.Begin);
                    copy = (T)serializer.Deserialize(ms);
                    return true;
                }
            }
            catch (Exception ex)
            {
                copy = default(T);
                onFailure(ex);
                return false;
            }
        }

        public static T ValueOrDefault<T>(this object o, T t)
        {
            if (o == null)
            {
                return default(T);
            }
            else
            {
                return t;
            }
        }

        /// <summary>
        /// Enumerate the sequence without performing any action on it
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumerable"></param>
        /// <returns></returns>
        public static IEnumerable<T> Enumerate<T>(this IEnumerable<T> enumerable)
        {
            enumerable.Run();
            
            return enumerable;
        }

        public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
        {
            return (enumerable == null || enumerable.Count() == 0);
        }
    }
}
